<?php

namespace App\Repositories\Admin;

use App\BaseRepository;
use App\Model\ActivityProduct;
use function GuzzleHttp\Psr7\str;
use Illuminate\Support\Facades\DB;

class ActivityRepository extends BaseRepository
{
    //模型名称
    protected $modelName = "App\Model\Activity";

    protected $appendCreatorAndUpdater = true;

    protected $appendUserId = true;

    protected $allowApiMethod = ['index','show','store','destroy','destroyBatch','simpleList'];

    protected function beforeListShow($model)
    {
        return $model->orderBy('start_time','desc')->orderBy('id','desc');
    }

    protected function relationLoad()
    {
        return ['nextActivity'];
    }


    protected function simpleListFiled()
    {
        return ['id','name'];
    }

    protected function getShowRespondData($model)
    {
        $model->products = DB::table('wine_product')
            ->whereRaw('`id` in (select product_id from activity_products where activity_id=?)',[$model->id])
            ->select('id','chname','name')->get();
        $model->lecturer = DB::table('t_user')->where('id','=',[$model->lecturer_id])
            ->select('id','name')->first();
        return $model;
    }

    protected function commonRules()
    {
        return [
            'name' => 'required',
            'toll' => 'required|in:1,0',
            'type' => 'required|in:article,poster',
            'participate_limit' => 'required',
            'start_time' => 'required',
            'end_time' => 'required',
            'deadline' => 'required|date',
            'product_ids' => 'required',
            'state' => 'required|in:publish,draft,finished',
        ];
    }

    //更新
    public function update($request, $id)
    {
        if(!$this->checkAuth('update')) {
            return $this->error;
        }

        if(!$this->updateValidate($id)) {
            return $this->failed($this->error);
        }

        $fillData = $this->getUpdateFillData();

        $model = $this->model($id)->fill($fillData);

        $originalModel = $model->getOriginal();

        if($model->beforeSave($this->request->all()) && $model->save() && $model->afterSave()){

            $this->afterUpdate($model);
            $this->commonSave($model);

            $respond = $this->getUpdateRespondData($model);

            $this->saveUpdateLog($model,$originalModel,$request,$id);
            return $this->success($respond);
        }

        return $this->failed('');
    }

    //自定义存储验证
    protected function processStoreValidate()
    {
        if (strtotime($this->request->input('end_time'))<strtotime($this->request->input('deadline'))){
            $this->error = "报名截止时间必须小于活动结束时间";
            return false;
        }
        return true;
    }

    //自定义更新验证
    protected function processUpdateValidate($id)
    {
        if (strtotime($this->request->input('end_time'))<strtotime($this->request->input('deadline'))){
            $this->error = "报名截止时间必须小于活动结束时间";
            return false;
        }
        return true;
    }

    protected function commonSave($model)
    {

        if ($this->request->has('product_ids')) {
            $ids = $this->request->input('product_ids');

            $rows = $ids?explode(',',$ids) : [];

            $db = DB::table('activity_products')->where('activity_id','=',$model->id);

            $o_ids = $db->pluck('product_id')->toArray();

            $db->whereIn('product_id',array_diff($o_ids,$rows))->delete();

            $rows = array_diff($rows,$o_ids);

            foreach ($rows as $row) {
                $m = new ActivityProduct();
                $m->product_id = $row;
                $m->activity_id = $model->id;
                $m->save();

            }
            return true;
        }
        return false;
    }

    protected function processDestroyValidate($id)
    {
        $c = DB::table('activity_orders')->where('activity_id','=',$id)->count();
        if ($c>0){
            $this->error = "此活动已有人参与！";
            return false;
        }
        return true;
    }
}